#ifndef _AC_CALYPSO_GLOBALFUNCTIONS
#define _AC_CALYPSO_GLOBALFUNCTIONS

namespace AirCrash {
namespace Calypso {

inline QRect scaleRect(const QRect& origRect, float scale) {
	return QRect(origRect.x() * scale, origRect.y() * scale, origRect.width() * scale, origRect.height() * scale);
}

inline QImage makeGrayScaleImage(const QImage& image) {
	QImage retImage = QImage(image.width(), image.height(), image.format());
	for (int y(0); y < image.height(); ++y) {
		for (int x(0); x < image.width(); ++x) {
			QRgb origPix(image.pixel(x, y));
			int gem((qRed(origPix) + qGreen(origPix) + qBlue(origPix)) / 3);
			retImage.setPixel(x, y, qRgb(gem, gem, gem));
		}
	}
	return retImage;
}

inline QImage IplToQImage(const IplImage * const iplImg) {
	int h = iplImg->height;
	int w = iplImg->width;
	int channels = iplImg->nChannels;
	QImage qimg(w, h, QImage::Format_ARGB32);
	char * data = iplImg->imageData;

	for (int y = 0; y < h; y++, data += iplImg->widthStep) 	{
		for (int x = 0; x < w; x++) 		{
			char r, g, b, a = 0;
			if (channels == 1) 			{
				r = data[x * channels];
				g = data[x * channels];
				b = data[x * channels];
			} else if (channels == 3 || channels == 4) {
				r = data[x * channels + 2];
				g = data[x * channels + 1];
				b = data[x * channels];
			}

			if (channels == 4) {
				a = data[x * channels + 3];
				qimg.setPixel(x, y, qRgba(r, g, b, a));
			} else {
				qimg.setPixel(x, y, qRgb(r, g, b));
			}
		}
	}
	return qimg;
}

inline IplImage * QImageToIplImage(const QImage& image) {
	IplImage *imgHeader = cvCreateImageHeader( cvSize(image.width(), image.height()), IPL_DEPTH_8U, 4);
	imgHeader->imageData = (char*) image.bits();

	uchar* newdata = (uchar*) malloc(sizeof(uchar) * image.byteCount());
	memcpy(newdata, image.bits(), image.byteCount());
	imgHeader->imageData = (char*) newdata;
	//cvClo
	return imgHeader;
}

inline float mmToPixel(float mm, float res) {
	float inch(mm * 0.0393700787f);
	return (inch * res);
}

inline QRect mmToPixel(QRect rect, float res) {
	QRect retValue;

	retValue.setX((rect.x() * 0.0393700787f) * res);
	retValue.setY((rect.y() * 0.0393700787f) * res);
	retValue.setWidth((rect.width() * 0.0393700787f) * res);
	retValue.setHeight((rect.height() * 0.0393700787f) * res);

	return retValue;
}

inline QSize mmToPixel(QSize size, float res) {
	QSize retValue;

	retValue.setWidth((size.width() * 0.0393700787f) * res);
	retValue.setHeight((size.height() * 0.0393700787f) * res);

	return retValue;
}

}
}

#endif